package unimelb.filesync.server.protocol;

import java.security.KeyPair;

import unimelb.filesync.common.crypto.CryptoUtils;
import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.message.RequestPublicKey;
import unimelb.filesync.common.message.ResponsePublicKey;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.network.NetworkService;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class SendPublicKeyPhase implements IFileSyncPhase {
    private final ProtocolContext context;

    private final CryptoUtils cryptoUtils;

    private final NetworkService networkService;

    public SendPublicKeyPhase(ProtocolContext context) {
        super();
        this.context = context;
        this.cryptoUtils = new CryptoUtils();
        this.networkService = new NetworkService();
    }

    @Override
    public void execute() {
        final NetworkConnection connection = context.getObject(ProtocolContext.HOT_LINE_CONNECTION);

        final NetworkMessage publicKeyRequest = networkService.readMessage(connection);
        if (publicKeyRequest == null) {
            System.exit(0);
        }

        final RequestPublicKey content = publicKeyRequest.getContent();
        if (content.isPublicKeyNeeded()) {
            System.out.println("Client does not request public key");
            final KeyPair keyPair = context.getObject(ProtocolContext.SERVER_KEY_PAIR);
            final String encodedKey = cryptoUtils.encodePublicKey(keyPair.getPublic());

            networkService.writeMessage(NetworkMessage.createPublicKeyResponseMsg(new ResponsePublicKey(encodedKey)), connection);
        } else {
            System.out.println("Sending public key to client");
            networkService.writeMessage(NetworkMessage.createPublicKeyResponseMsg(new ResponsePublicKey(null)), connection);
        }
    }

}
